package com.changgou.goods.task;

import com.changgou.goods.pojo.Brand;
import com.changgou.goods.pojo.Category;
import com.changgou.goods.pojo.ImportLog;
import com.changgou.goods.pojo.Spu;
import com.changgou.goods.service.BrandService;
import com.changgou.goods.service.CategoryService;
import com.changgou.goods.service.ImportLogService;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Jiang Yilin
 * @title: GoodsImptTask
 * @projectName changgou_parent
 * @description: TODO
 * @date 2020/3/710:28
 */
@Component
public class GoodsImptTask {

    @Autowired
    ImportLogService importLogService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SpuService spuService;

    @Autowired
    IdWorker idWorker;

    @Scheduled(cron = "0/10 * * * * ?")
    public void imptSpu(){
        //1.查询上传状态的文件列表
        ImportLog importLog = new ImportLog();
        importLog.setStatus("upload");
        List<ImportLog> importLogs = importLogService.queryByBean(importLog);
        if(importLogs !=null && importLogs.size()>0){
            importLogs.forEach(log->{
                String file_path = log.getFilePath();
                List<String> arrayList = new ArrayList<>();
                try {
                    FileReader fr = new FileReader(file_path+ File.separator+log.getFileName());
                    BufferedReader bf = new BufferedReader(fr);
                    String str;
                    int successCount = 0;
                    int errorCount = 0;
                    List<String> errorList = new ArrayList<>();
                    // 按行读取字符串
                    while ((str = bf.readLine()) != null) {
                        arrayList.add(new String(str.getBytes(),"UTF-8"));
                        if(arrayList.size()%2000==0){
                            for (String line : arrayList) {
                                boolean resultFlag = dealLine(line);
                                if(resultFlag){
                                    successCount +=1;
                                }else{
                                    errorCount += 1;
                                    errorList.add(line);
                                }
                            }
                            arrayList.clear();
                        }
                    }
                    if(arrayList.size()>0){
                        for (String line : arrayList) {
                            boolean resultFlag = dealLine(line);
                            if(resultFlag){
                                successCount +=1;
                            }else{
                                errorCount += 1;
                                errorList.add(line);
                            }
                        }
                        arrayList.clear();
                    }
                    log.setErrorCount(errorCount);
                    log.setSuccessCount(successCount);
                    log.setStatus("import");
                    //文件导出
                    if(errorCount>0){
                        String errorFileName = "error_"+log.getFileName();
                        log.setErrorFileName(errorFileName);
                        createErrorFile(errorList,log.getFilePath()+File.separator+errorFileName);
                    }
                    importLogService.update(log);
                    bf.close();
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
        }
    }

    private boolean dealLine(String line){
        boolean result = false;
        String[] array = line.split("\\|");
        if(array.length==9){
            Spu spu = new Spu();

            spu.setId(String.valueOf(idWorker.nextId()));
            spu.setName(array[0]);
            spu.setCaption(array[1]);


            //根据名称查Id
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("name",array[2]);
            List<Brand> list = brandService.findList(searchMap);
            if(list!=null && list.size()>0){
                spu.setBrandId(list.get(0).getId());
            }
            //......

            spuService.addSpu(spu);
            result =true;
        }

        return result;
    }

    private void createErrorFile(List<String> errorList,String errorFilePath){

        try {
            IOUtils.writeLines(errorList,"UTF-8",new FileOutputStream(errorFilePath),Charset.forName("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
